<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option  value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in arr" :key="item.id">
          <td>{{index+1}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click.prevent="delFn(item.id)">删除</button>
            <button @click.prevent="redact(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return{
      name:'',
      age:0,
      gender:'男',
      flag:'',//标记 用于区分按钮点击了是添加还是修改功能 
      arr:[{
        id:1,
      name:'韩枫',
      age:18,
      gender:'男',
    }]
    }
  },
  methods:{
    addFn(){
      if (this.flag==='') {
        //添加功能
        this.arr.push({
          id:+new Date(),
          name:this.name,
          age:this.age,
          gender:this.gender,
        })
      }else{
        //因为flag不等于'' 所以会走到此函数
        //修改是把输入框的值作为flag要修改对象的具体值
        this.flag.name=this.name
        this.flag.age=this.name
        this.flag.gender=this.gender
      }
      //清空输入框的值
      this.name=''
      this.age=''
      this.gender='男'
      //重置flag的值,不然下一次添加还是属于修改
      this.flag=''
    },
    delFn(id){
      this.arr=this.arr.filter((item)=>item.id!==id)
    },
    redact(id){
      const obj = this.arr.find((item)=>item.id===id)

      this.flag = obj


      const {name,age,gender} = obj

      this.name=name
      this.age=age
      this.gender=gender
    }
  },
  
}
</script>
